﻿using MySSO.Core.Entity;
using MySSO.Core.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MySSO.Core.Service
{
    public class AdminVisitService 
    {
        private readonly AdminVisitLogRecordRepository _adminVisitLogRecordRepository;

        private readonly LogRecordRefurlRepository _logRecordRefurlRepository;

        private readonly WebHelper _webHelper;

        public const string BASE_KEY = "SHUTDOWN";

        public const string Record_Cookie = "new_g_00_d";
        public AdminVisitService()
        {
            _webHelper = new WebHelper();
            _adminVisitLogRecordRepository = new AdminVisitLogRecordRepository();
            _logRecordRefurlRepository = new LogRecordRefurlRepository();
        }
        /// <summary>
        /// 访问记录
        /// </summary>
        public void AccessRecord()
        {
            if (!_webHelper.SupportCookies())
            {
                return;
            }
            long recordId = GetVistRecordId();
            if (recordId > 0)
            {
                return;
            }

            AdminVisitLogRecordEntity entity = new AdminVisitLogRecordEntity();
            entity.IpAddress = _webHelper.GetCurrentIpAddress();
            entity.Create_Time = DateTime.Now;
            recordId = _adminVisitLogRecordRepository.InsertAdminVisitLogRecordEntity(entity);
            string desrid = DecryptString.DESEncrypt(recordId.ToString(), BASE_KEY);
            _webHelper.SetCookie(Record_Cookie, desrid, DateTime.Now.AddYears(2));

        }


        public void AccessRefurlRecord()
        {

            long recordId = GetVistRecordId();
            if (recordId <= 0)
            {
                return;
            }

            LogRecordRefurlEntity entity = new LogRecordRefurlEntity();
            entity.RID = recordId;
            entity.IpAddress = _webHelper.GetCurrentIpAddress();
            entity.Refurl = _webHelper.GetRequestUrl();
            entity.System = _webHelper.GetUserAgent();
            entity.Browser = _webHelper.GetBrowser();
            entity.Create_Time = DateTime.Now;
            _logRecordRefurlRepository.InsertLogRecordRefurlEntity(entity);
        }

        /// <summary>
        /// 从cookie中获取recordid
        /// </summary>
        /// <returns></returns>
        public long GetVistRecordId()
        {
            string record = _webHelper.GetCookie(Record_Cookie);
            long RID = 0;
            if (string.IsNullOrWhiteSpace(record))
            {
                return RID;
            }
            else
            {
                RID = Convert.ToInt64(DecryptString.DESDecrypt(record, BASE_KEY));
                return RID;
            }
        }
    }
}
